package com.sqj.proxyPattern.dynamicProxy;

import com.sqj.proxyPattern.DynamicDataSourceEntry;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OrderServiceDynamicProxy implements InvocationHandler {
    private SimpleDateFormat yearFormat=new SimpleDateFormat("yyyy");
    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object invoke = method.invoke(target, args);
        after();
        return proxy;
    }

    private void before(Object target){
        System.out.println("Proxy before method");
        try {
            Date date = (Date) target.getClass().getMethod("getCreateDatetime").invoke(target);
            Integer dbRouter = Integer.valueOf(yearFormat.format(date));
            System.out.println("自动分配到【DB_"+dbRouter+"】数据源处理器");
            DynamicDataSourceEntry.set(dbRouter);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }

    private void after(){
        System.out.println("Proxy after method");
    }
}
